/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { omitBy } from 'lodash';
import { useEffect, useMemo, useState } from 'react';

enum Continuity {
  Position = 0,
  Tangent = 1,
  Curvature = 3,
}

enum KeepOtherEnd {
  None = -1,
  Position = 0,
  Tangent = 1,
  Curvature = 2,
}

type FormData = {
  surface1?: pickedFaceData;
  edge1?: pickedLineData;
  point1?: pickedVertexData;
  reverse1: boolean;
  continuity: Continuity;
  surface2?: pickedFaceData;
  edge2?: pickedLineData;
  point2?: pickedVertexData;
  reverse2: boolean;
  keepOtherEnd: KeepOtherEnd;
  isPrecise: boolean;
  tol0?: number;
  tol1?: number;
  tol2?: number;
  tension1: number;
  tension3: number;
};

type ParamsSurface = {
  id: string;
  edge: string;
  point: string;
  reverse: boolean;
};

type Params = {
  isBothChange: false;
  surface1: ParamsSurface & {
    continuity: Continuity;
    keepOtherEnd: KeepOtherEnd;
  };
  surface2: ParamsSurface;
  isPrecise: boolean;
  tol0: number;
  tol1: number;
  tol2: number;
  tension1: number;
  tension3: number;
};

function CommandMatchSurface({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData = {
    continuity: Continuity.Position,
    reverse1: false,
    keepOtherEnd: KeepOtherEnd.Position,
    reverse2: false,
    isPrecise: false,
    tension1: 0.3,
    tension3: 0.3,
  } as FormData;

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  const execute = async (preview: boolean) => {
    const {
      surface1,
      edge1,
      point1,
      reverse1,
      surface2,
      reverse2,
      continuity,
      keepOtherEnd,
      edge2,
      point2,
      isPrecise,
      tol0,
      tol1,
      tol2,
      tension1,
      tension3,
    } = formData;

    const params: Params = {
      isBothChange: false,
      surface1: {
        id: surface1.meshId,
        edge: edge1.edgeId,
        point: point1?.vertexId,
        reverse: reverse1,
        continuity,
        keepOtherEnd,
      },
      surface2: {
        id: surface2.meshId,
        edge: edge2.edgeId,
        point: point2?.vertexId,
        reverse: reverse2,
      },
      isPrecise,
      tol0: isPrecise ? tol0 : null,
      tol1: isPrecise ? tol1 : null,
      tol2: isPrecise ? tol2 : null,
      tension1,
      tension3,
    };

    await confirmCommand({ type: 'Match', a: params }, preview);
  };

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }

    const params: Params = props.params;

    const {
      surface1,
      surface2,
      isPrecise,
      tol0,
      tol1,
      tol2,
      tension1,
      tension3,
    } = params;

    await initEditDependency([
      surface1.id,
      surface1.edge,
      surface1.point,
      surface2.id,
      surface2.edge,
      surface2.point,
    ]);

    setFormData({
      surface1: picker.generatePickObjByPickID(surface1.id) as pickedFaceData,
      edge1: picker.generatePickObjByPickID(surface1.edge) as pickedLineData,
      point1: picker.generatePickObjByPickID(
        surface1.point,
      ) as pickedVertexData,
      reverse1: surface1.reverse,
      continuity: surface1.continuity,
      surface2: picker.generatePickObjByPickID(surface2.id) as pickedFaceData,
      edge2: picker.generatePickObjByPickID(surface2.edge) as pickedLineData,
      point2: picker.generatePickObjByPickID(
        surface2.point,
      ) as pickedVertexData,
      reverse2: surface1.reverse,
      keepOtherEnd: surface1.keepOtherEnd,
      isPrecise,
      tol0: isPrecise ? tol0 : null,
      tol1: isPrecise ? tol1 : null,
      tol2: isPrecise ? tol2 : null,
      tension1,
      tension3,
    });
  }, []);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, clear, isLoading } =
    useCommand('cmd-match-surface', {
      commandName: 'CreateSurface',
      editDxid: props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const isFormDataValid = () => {
    const {
      surface1,
      edge1,
      surface2,
      edge2,
      isPrecise,
      tol0,
      tol1,
      tol2,
      tension1,
      tension3,
    } = formData;

    const isPreciseValid =
      !isPrecise || (tol0 != null && tol1 != null && tol2 != null);

    return (
      surface1 != null &&
      edge1 != null &&
      surface2 != null &&
      edge2 != null &&
      isPreciseValid &&
      tension1 != null &&
      tension3 != null
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = useMemo(() => {
    return omitBy(
      {
        type: 'object',
        properties: {
          surface1: {
            type: 'string',
            format: PickInputRJSFFormat.PickSurface,
          },
          edge1: {
            type: 'string',
            format: PickInputRJSFFormat.PickCurve,
          },
          point1: {
            type: 'string',
            format: PickInputRJSFFormat.PickVertex,
          },
          reverse1: {
            type: 'boolean',
            title: '曲面1反转',
          },
          continuity: {
            title: '曲面1连续方式',
            type: 'number',
            oneOf: [
              {
                type: 'number',
                title: '位置',
                const: 0,
              },
              {
                type: 'number',
                title: '切线',
                const: 1,
              },
              {
                type: 'number',
                title: '曲率',
                const: 3,
              },
            ],
            default: 0,
          },
          surface2: {
            type: 'string',
            format: PickInputRJSFFormat.PickSurface,
          },
          edge2: {
            type: 'string',
            format: PickInputRJSFFormat.PickCurve,
          },
          point2: {
            type: 'string',
            format: PickInputRJSFFormat.PickVertex,
          },
          keepOtherEnd: {
            title: '曲面2连续方式',
            type: 'number',
            oneOf: [
              {
                type: 'number',
                title: '不保持',
                const: -1,
              },
              {
                type: 'number',
                title: '位置',
                const: 0,
              },
              {
                type: 'number',
                title: '切线',
                const: 1,
              },
              {
                type: 'number',
                title: '曲率',
                const: 2,
              },
            ],
            default: 0,
          },
          reverse: {
            type: 'boolean',
            title: '曲面2反转',
          },
          isPrecise: {
            type: 'boolean',
            title: '容差限制',
          },
          tol0: formData.isPrecise && {
            type: 'number',
            title: '位置容差',
            format: NumberInputFormat.Real,
          },
          tol1: formData.isPrecise && {
            type: 'number',
            title: '位置公差',
            format: NumberInputFormat.Real,
          },
          tol2: formData.isPrecise && {
            type: 'number',
            title: '曲率相对误差公差',
            format: NumberInputFormat.Real,
          },
          tension1: {
            type: 'number',
            title: '相切时张度',
            format: NumberInputFormat.Real,
          },
          tension3: {
            type: 'number',
            title: '曲率时张度',
            format: NumberInputFormat.Real,
          },
        },
      },
      (v) => !v,
    );
  }, [formData.isPrecise]);

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        surface1: {
          'ui:placeholder': '请输入曲面1(将被修改)',
          'ui:autofocus': true,
        },
        edge1: {
          'ui:placeholder': '请输入曲面1的边界',
        },
        point1: {
          'ui:placeholder': '曲面1边界上的点(选填)',
        },
        surface2: {
          'ui:placeholder': '请输入曲面2',
        },
        edge2: {
          'ui:placeholder': '请输入曲面2的边界',
        },
        point2: {
          'ui:placeholder': '曲面2边界上的点(可选)',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdMatchSurface: CurvedBaseCommand = {
  id: 'CmdMatchSurface',
  label: 'command.match-surface',
  icon: 'commands/curved/match-surface',
  create: (label, onClose, props) => (
    <CommandMatchSurface
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
